package mysql;


/**
 * @ClassName MysqlPacket
 * @Description TODO
 * @Author fengk
 * @Date 2018/8/25
 */

public class MysqlPacketHeader implements MysqlPacketInter{
    private int payloadLength;
    private byte sequenceId=(byte) 0x00;

    /**
     *int<3>	payload_length
     * int<1>	sequence_id
     * @param data
     */
    public void encode(byte[] data) {
        if (data == null || data.length != 4) {
            throw new IllegalArgumentException("invalid header data. It can't be null and the length must be 4 byte.");
        }
        this.payloadLength = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8) | ((data[2] & 0xFF) << 16);
        this.setSequenceId(data[3]);
    }

    /**
     *
     * @return
     */
    public byte[] decode() {
        byte[] data = new byte[4];
        data[0] = (byte) (payloadLength & 0xFF);
        data[1] = (byte) (payloadLength >>> 8);
        data[2] = (byte) (payloadLength >>> 16);
        data[3] = getSequenceId();
        return data;
    }

    public int getPayloadLength() {
        return payloadLength;
    }

    public void setPayloadLength(int payloadLength) {
        this.payloadLength = payloadLength;
    }

    public byte getSequenceId() {
        return sequenceId;
    }

    public void setSequenceId(byte sequenceId) {
        this.sequenceId = sequenceId;
    }
}
